package com.cet.qz.unit01.chapter1_3;

/**
 * @program: algorithm
 * @description: 文本编辑器的缓冲区   参考链接：https://blog.csdn.net/qq_34446253/article/details/77849576
 * @author: 陈恩涛
 * @create: 2021-04-25 11:12
 **/
public class Buffer {

    /**
     *    stack(before) 栈顶 | 栈顶  stack(after)
     */

    //光标前
    private Stack<Character> before;
    //光标后
    private Stack<Character> after;

    private int n;

    public Buffer() {
        before = new Stack<>();
        after = new Stack<>();
        n = 0;
    }

    /**
     * 在光标位置插入字符c
     * @param c
     */
    public void insert(char c) {
        before.push(c);
        n++;
    }

    /**
     * 删除并返回光标位置的字符
     * @return
     */
    public char delete() {
        if (before.isEmpty()) {
            throw new RuntimeException("光标处无字符！");
        } else {
            n--;
            return before.pop();
        }
    }

    /**
     * 将光标左移K个位置
     * @param k
     */
    public void left(int k) {
        //若左移位置数大于before栈的大小，则只能左移before.size()
        if (k > before.size()) {
            k = before.size();
        }
        for (int i = 0; i < k; i++) {
            after.push(before.pop());
        }
    }

    /**
     * 将光标右移k个位置
     * @param k
     */
    public void right(int k) {
        //若右移位置数大于before栈的大小，则只能右移after.size()
        if (k > after.size()) {
            k = after.size();
        }
        for (int i = 0; i < k; i++) {
            before.push(after.pop());
        }
    }

    /**
     * 缓冲区中的字符数量
     * @return
     */
    public int size() {
        return n;
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        for (Character c : before) {
            result.append(c);
        }
        result.append("|");
        for (Character c : after) {
            result.append(c);
        }
        return result.toString();
    }

    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        buffer.insert('a');
        buffer.insert('a');
        buffer.insert('a');
        buffer.insert('a');
        buffer.insert('a');
        buffer.insert('a');
        buffer.insert('a');
        buffer.insert('a');
        buffer.insert('a');
        buffer.left(2);
        System.out.println(buffer.delete());
        buffer.right(100);
        System.out.println(buffer);
    }
}
